/**
 * Copyright (C) 2024-2030 Super BilGen & 超亿时代信息技术股份有限公司.All Rights Reserved.
 */
package cn.com.yang.thread;

/**
 * @Model cn.com.yang.thread.CompletionServiceExample
 * @Desc  TODO
 * @author yangyijin
 * @since 2025年3月21日-下午5:35:02
 */
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class CompletionServiceExample {
    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        // 创建一个基于该线程池的 CompletionService
        CompletionService<String> completionService = new ExecutorCompletionService<>(executor);
        
        // 提交多个任务
        List<Callable<String>> tasks = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            final int taskId = i;
            tasks.add(() -> {
                // 模拟任务执行时间
                Thread.sleep((long) (Math.random() * 2000));
                return "Task " + taskId + " completed";
            });
        }
        
        // 提交所有任务到 CompletionService
        for (Callable<String> task : tasks) {
            completionService.submit(task);
        }
        
        // 获取并处理完成的任务结果
        for (int i = 0; i < tasks.size(); i++) {
            try {
                Future<String> future = completionService.take(); // 阻塞直到有任务完成
                String result = future.get(); // 获取任务结果
                System.out.println(result);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        
        // 关闭线程池
        executor.shutdown();
    }
}